package com.lcx.handler;

import com.lcx.client.UserServiceImpl;
import com.lcx.request.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
public class UserServiceHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {

    //注入spring上下文
    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        UserServiceHandler.applicationContext = applicationContext;
    }

    //当客户端读取数据时该方法被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //把读取的对象转换
        RpcRequest rpcRequest = (RpcRequest) msg;
        String className = rpcRequest.getClassName();
        String methodName = rpcRequest.getMethodName();
        Object[] args = rpcRequest.getParameters();
        Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
        //根据spring上下文获取实例class
        Class<?> aClass = Class.forName(className);
        Object bean = applicationContext.getBean(aClass);
        //根据方法名，参数类型获取method
        Method method = aClass.getDeclaredMethod(methodName, parameterTypes);
        //根据实例，参数invoke
        method.invoke(bean,args);
        ctx.writeAndFlush("success");

        //注意:客户端会传来一个参数，UserService#sayHello#are you ok
        //1、判断当前请求是否符合规则
        /*if (msg.toString().startsWith("UserService")){
            //2、如果符合规则，调用实现类得到一个result
            UserServiceImpl userService = new UserServiceImpl();
            String s = msg.toString();
            String ss = s.substring(s.lastIndexOf("#")+1);
            String result = userService.sayHello(ss);

            //3、把调用实现类的方法获得的结果写到客户端
            ctx.writeAndFlush(result);
        }*/

    }
}
